package com.sxm.yiwei.fragments;


import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.FWDiscussAdapter;
import com.sxm.yiwei.beans.DiscussBeans;
import com.sxm.yiwei.tools.ErrType;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/** 图片评论
 * A simple {@link Fragment} subclass.
 */
public class DiscussPicFragment extends Fragment {


    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private String id;
    private int  page = 1;
    private PullToRefreshListView piclist;
    private FWDiscussAdapter adapter;

    public DiscussPicFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_discuss_pic, container, false);
        sharedPreferences = getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        Intent intent = getActivity().getIntent();
        id = intent.getStringExtra("id");

        piclist = (PullToRefreshListView) view.findViewById(R.id.pic_listview);
            getListData(page);

        return view;
    }


    // 获取信息列表
    private void getListData(int page) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.GETPINGLUNLIST);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject object = new JSONObject();

        object.put("status","2");
        object.put("serviceId",id);
        object.put("pageNo",page+"");
        object.put("pageSize","20");

        params.addParameter("params",object.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d("tag", "onSuccess: 图片--"+result+"//"+id);

                getData(result);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("tag", "onSuccess: 图片--"+ex);
                ErrType.errType(getActivity(),ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    // 获取数据
    private void getData(String result) {

        List<DiscussBeans.DataBean> mlist = new ArrayList<>();
        JSONObject object = JSON.parseObject(result);
        final JSONArray data = object.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
            String anonymous = obj1.getString("anonymous");
            String content = obj1.getString("content");
            Integer createTime = obj1.getInteger("createTime");
            String nickname = obj1.getString("nickname");
            Integer score = obj1.getInteger("score");
            String userAvatar = obj1.getString("userAvatar");
            JSONArray commentImage = obj1.getJSONArray("commentImage");
            DiscussBeans.DataBean dataBean = new DiscussBeans.DataBean();
            dataBean.setAnonymous(Integer.valueOf(anonymous));
            dataBean.setContent(content);
            dataBean.setUserAvatar(userAvatar);
            dataBean.setCreateTime(Long.valueOf(createTime));
            dataBean.setNickname(nickname);
            dataBean.setScore(score);
            dataBean.setCommentImage(commentImage);
            mlist.add(dataBean);
        }

        adapter = new FWDiscussAdapter(getActivity(),mlist);
        piclist.setAdapter(adapter);

        piclist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                if (data.size()<20){

                }else {
                    page++;
                }
                getListData(page);
                new FinishRefresh().execute();
            }
        });
        adapter.notifyDataSetChanged();
    }

    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapter.notifyDataSetChanged();
            piclist.onRefreshComplete();
        }
    }
}
